﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

namespace Vcm
{
    public class CryptCardData
    {
        public readonly string Name;
        public readonly string Type;
        public readonly string Clan;
        public readonly bool IsAdv;
        public readonly string Group;
        public readonly string Capacity;
        public readonly string[] Disciplines;
        public readonly string Text;
        public readonly string Illustrator;
        public int Copies;

        private static readonly DisciplineComparer _disciplineComparer = new DisciplineComparer();
        private static bool _getColumnCopies = true;

        public CryptCardData(DataRow card)
        {
            Name = card["Name"].ToString().Trim().Replace("(TM)", "™");
            Type = card["Type"].ToString().Trim();
            Clan = card["Clan"].ToString().Trim();
            IsAdv = string.Equals(card["Adv"].ToString().Trim(), "Advanced", StringComparison.InvariantCultureIgnoreCase);
            Group = card["Group"].ToString().Trim();
            Capacity = card["Capacity"].ToString().Trim();

            Disciplines = card["Disciplines"].ToString().Trim().Split(' ').Where(d => d.Length > 0).OrderBy(d => d, _disciplineComparer).ToArray();
            Text = card["Card Text"].ToString().Trim().Replace("(TM)", "™");
            var artist = card["Artist"].ToString().Trim();
            var artists = artist.Split(';');
            Illustrator = artists[artists.Length - 1];

            _getColumnCopies &= card.Table.Columns.Contains("Copies");
            Copies = _getColumnCopies ? int.Parse(card["Copies"].ToString()) : 1;
        }

        public string CorrectedName
        {
            get
            {
                const string the = ", The";
                return Name.EndsWith(the)
                    ? "The " + Name.Substring(0, Name.Length - the.Length)
                    : Name;
            }
        }

        private class DisciplineComparer : IComparer<string>
        {
            public int Compare(string x, string y)
            {
                var isXInferior = x[0] >= 'a' && x[0] <= 'z';
                var isYInferior = y[0] >= 'a' && y[0] <= 'z';
                if (isXInferior == isYInferior)
                    return string.Compare(x, y, StringComparison.InvariantCulture);
                return isXInferior
                    ? -1
                    : 1;
            }
        }
    }
}
